using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Forum.Entity.Generate.MetaDataEntity
{
    /// <summary>
    /// mssql数据库转实体模型
    /// </summary>
    public class OracleDbToEntity
    {
        /// <summary>
        /// 数据操作
        /// </summary>
        public DapperOracleContext dbhelper { get; set; }

        /// <summary>
        /// 表名
        /// </summary>
        public string tablename { get; set; }

        /// <summary>
        /// 数据库名
        /// </summary>
        public string dbname { get; set; }

        /// <summary>
        /// 命名空间名
        /// </summary>
        public string spacename { get; set; }

        /// <summary>
        /// 需要增加的字符串
        /// </summary>
        //public string addusing { get; set; }

        public List<string> addusing { get; set; } = new List<string>();

        /// <summary>
        /// 继承字段
        /// </summary>
        public string inherit { get; set; }

        /// <summary>
        /// 长整形继承类名称
        /// </summary>
        public string inheritLong { get; set; }

        /// <summary>
        /// 继承字段没有默认id
        /// </summary>
        public string inheritNoId { get; set; }

        /// <summary>
        /// 排除字段
        /// </summary>
        public List<string> ignoreColumn { get; set; }

        /// <summary>
        /// 字符串
        /// </summary>
        private StringBuilder sb = new StringBuilder();

        /// <summary>
        /// 组合using语句
        /// </summary>
        public string dousing()
        {
            sb = new StringBuilder();
            //sb.Append("using System;");
            //sb.Append("\r");
            //sb.Append("using System.Collections.Generic;");
            //sb.Append("\r");
            //sb.Append("using System.Text;");
            //sb.Append("\r\n");

            if (addusing?.Count > 0)
            {
                addusing.ForEach(us =>
                {
                    sb.Append($"using {us};");
                    sb.Append("\r\n");
                });
            }

            sb.Append($"namespace {spacename}");
            sb.Append("\r\n");
            sb.Append("{");
            sb.Append("\r\n");
            doclass();
            dotype();

            if (tablename.Length <= 7 ||
                tablename.Substring(tablename.Length - 7).ToLower() != "_expand")
            {
                //doActive();
                doGetByid();
            }
            //结尾
            doEnding();
            return sb.ToString();
        }

        /// <summary>
        /// 查询表名，生成类对象
        /// </summary>
        private void doclass()
        {
            string StrSql = $@"SELECT
    a.TABLE_NAME as TABLE_NAME,
    a.comments as TABLE_COMMENT
FROM user_tab_comments a
WHERE a.Table_Name='{tablename}'";
            var obj = dbhelper.Query<TableEntity>(StrSql).ToList().FirstOrDefault();

            if (obj != null)
            {
                sb.Append($@"    /// <summary>");
                sb.Append("\r\n");
                if (!string.IsNullOrWhiteSpace(obj.TABLE_COMMENT))
                {
                    sb.Append($"    /// {obj.TABLE_COMMENT.Trim().Replace("\r", "").Replace("\n", "")}");
                    sb.Append("\r\n");
                }
                else {
                    sb.Append($"    /// 未知实体");
                    sb.Append("\r\n");
                }
                sb.Append("    /// </summary>");
                sb.Append("\r\n");
                //sb.Append("    [Table(\"" + obj.TABLE_NAME + "\")]");
                //sb.Append("\r\n");

                //if (!string.IsNullOrWhiteSpace(inherit))
                //{
                //    if ((obj.TABLE_NAME.Length > 7 &&
                //        obj.TABLE_NAME.Substring(obj.TABLE_NAME.Length - 7).ToLower() == "_expand"))
                //    {
                //        sb.Append($"    public class {obj.TABLE_NAME}");
                //    }
                //    else
                //    {
                //        sb.Append($"    public class {obj.TABLE_NAME} : {inherit}");
                //    }
                //}
                //else
                //{
                //    sb.Append($"    public class {obj.TABLE_NAME}");
                //}
                //if (!string.IsNullOrWhiteSpace(inheritNoId))
                //{
                //    sb.Append($"    public class {obj.TABLE_NAME} : {inheritNoId}");
                //}
                //else
                //{
                //    sb.Append($"    public class {obj.TABLE_NAME}");
                //}
                sb.Append($"    public class {obj.TABLE_NAME}");
                sb.Append("\r\n");
                sb.Append(@"    {");
            }
        }

        /// <summary>
        /// 生成字段
        /// </summary>
        private void dotype()
        {
            string StrSql = $@"select
     a.column_name AS COLUMN_NAME,
     b.DATA_TYPE AS DATA_TYPE,
     a.comments AS COLUMN_COMMENT
from user_col_comments  a
left join user_tab_columns b on a.table_name = b.TABLE_NAME
where a.Table_Name='{tablename}' and a.column_name = b.COLUMN_NAME";

            var obj = dbhelper.Query<ColumnEntity>(StrSql).ToList();

            var InsertSb = new StringBuilder();
            var ValueSb = new StringBuilder();

            if (obj?.Count > 0)
            {
                InsertSb.Append($"INSERT INTO {tablename} (");

                ValueSb.Append("\r\n");
                ValueSb.Append($"                                        VALUES (");
                foreach (var item in obj)
                {
                    if (item.COLUMN_NAME.Trim().ToLower() != "id" &&
                        item.DATA_TYPE.Trim().ToLower() == "bigint")
                    {
                        sb = sb.Replace($": {inheritNoId}", $": {inheritLong}");//   inherit, inheritLong);
                    }
                    else if (item.COLUMN_NAME.Trim().ToLower() == "id")
                    {
                        sb = sb.Replace($": {inheritNoId}", $": {inherit}");
                    }

                    if (item.COLUMN_NAME.Trim().ToLower() == "id" &&
                       (item.DATA_TYPE.Trim().ToLower() == "bigint" || item.DATA_TYPE.Trim().ToLower() == "int"))
                    {
                        // 如果是整形自增id，则新增接口不需要创建
                    }
                    else
                    {
                        //InsertSb.Append("\r\n");
                        InsertSb.Append($"{item.COLUMN_NAME},");

                        //ValueSb.Append("\r\n");
                        ValueSb.Append($":{item.COLUMN_NAME},");
                    }

                    //if (item.COLUMN_NAME.Trim().ToLower() == "isactive" ||
                    //    item.COLUMN_NAME.Trim().ToLower() == "cuser" ||
                    //    item.COLUMN_NAME.Trim().ToLower() == "uuser" ||
                    //    item.COLUMN_NAME.Trim().ToLower() == "cdate" ||
                    //    item.COLUMN_NAME.Trim().ToLower() == "udate" ||
                    //    item.COLUMN_NAME.Trim().ToLower() == "id")
                    //{
                    //    continue;
                    //}

                    sb.Append("\r\n");
                    sb.Append("        /// <summary>");
                    sb.Append("\r\n");
                    if (!string.IsNullOrWhiteSpace(item.COLUMN_COMMENT))
                        sb.Append($"        /// {item.COLUMN_COMMENT.Trim().Replace("\r", "").Replace("\n", "")}");
                    else
                        sb.Append($"        /// ");

                    sb.Append("\r\n");
                    sb.Append("        /// </summary>");

                    string datatype = "string";
                    switch (item.DATA_TYPE.ToLower())
                    {
                        case "varchar":
                        case "nvarchar":
                        case "text":
                        case "varchar2":
                            datatype = "string";
                            break;

                        case "datetime":
                        case "datetime2":
                        case "date":
                        case "time":
                        case "timestamp(6)":
                            datatype = "DateTime?";
                            break;

                        case "bigint":
                        case "int":
                        case "smallint":
                            datatype = "int";
                            break;

                        case "bit":
                            datatype = "bool";
                            break;

                        case "float":
                            datatype = "float";
                            break;

                        case "number":
                        case "decimal":
                            datatype = "decimal?";
                            break;
                    }
                    sb.Append("\r\n");

                    if (item?.COLUMN_KEY?.Trim().ToUpper() == "PRI")
                    {
                        sb.Append("        [Key]");
                        sb.Append("\r\n");
                    }

                    sb.Append($@"        public {datatype} {item.COLUMN_NAME}");
                    sb.Append(" { get; set; }");
                }

                if (InsertSb.ToString().Substring(InsertSb.ToString().Length - 1, 1) == ",")
                {
                    InsertSb.Remove(InsertSb.Length - 1, 1);
                }
                InsertSb.Append(")");

                if (ValueSb.ToString().Substring(ValueSb.ToString().Length - 1, 1) == ",")
                {
                    ValueSb.Remove(ValueSb.Length - 1, 1);
                }
                ValueSb.Append(");");
            }
            sb.Append("\r\n");
            sb.Append("        /// <summary>");
            sb.Append("\r\n");
            sb.Append($"        /// 新增语句");
            sb.Append("\r\n");
            sb.Append("        /// </summary>");
            sb.Append("\r\n");

            sb.Append($"        public string InserSql() => @\" {InsertSb.ToString().ToUpper()}{ValueSb.ToString()}\";");
            sb.Append("\r\n");

            //INSERT INTO TB_SYS_OPERATOR_LOG(GUID, ACTIVE_FLAG, DOC_NO, OPERATOR, DOC_STATUS, CREATE_BY, CREATE_TIME) VALUES(:GUID, 'Y',:DOC_NO,:OPERATOR,:DOC_STATUS,:CREATE_BY, SYSDATE)
        }

        /// <summary>
        /// 激活方法
        /// </summary>
        private void doActive()
        {
            sb.Append("\r\n");
            sb.Append("        /// <summary>");
            sb.Append("\r\n");
            sb.Append($"        /// 激活语句");
            sb.Append("\r\n");
            sb.Append("        /// </summary>");
            sb.Append("\r\n");

            sb.Append($"        public string ActiveSql() => @\" UPDATE {tablename}] ");
            sb.Append("\r\n");
            sb.Append("                                        SET IsActive = @IsActive");
            sb.Append("\r\n");
            sb.Append("                                        where id = @id;\";");
            sb.Append("\r\n");
        }

        /// <summary>
        /// 通过id获取对象
        /// </summary>
        private void doGetByid()
        {
            sb.Append("\r\n");
            sb.Append("        /// <summary>");
            sb.Append("\r\n");
            sb.Append($"        /// 通过id查询对象");
            sb.Append("\r\n");
            sb.Append("        /// </summary>");
            sb.Append("\r\n");

            sb.Append("        public string GetByidSql() => @\" SELECT * ");
            sb.Append("\r\n");
            sb.Append($"                                        FROM {tablename} ");
            sb.Append("\r\n");
            sb.Append("                                        WHERE GUID = :GUID\";");
            sb.Append("\r\n");
        }

        /// <summary>
        /// 执行结尾输出
        /// </summary>
        public void doEnding()
        {
            sb.Append("    }");
            sb.Append("\r\n");
            sb.Append("}");
        }
    }
}